package com.example.shangguigu.des_aes;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @DESCRIPTION:
 * @USER: shg
 * @DATE: 2023/2/25 0:04
 */
public class DesAndAesDemo {

    public static void main(String[] args) throws Exception{
        // 明文
        String source = "硅谷";

        // 定义DES加密算法的密钥key
        String key = "12345678";

        // 规定加密所使用的算法
        String algorithm = "DES";

        String transformation = "DES";

        String desEncryptResult = desEncrypt(source, key, transformation, algorithm);// DES加密
        System.out.println("加密数据："+desEncryptResult);
        String desDecryptResult = desDecrypt(desEncryptResult, key, transformation, algorithm);// DES解密
        System.out.println("解密数据："+desDecryptResult);
    }

    // DES解密
    private static String desDecrypt(String encryptString,String key,String transformation,String algorithm) throws Exception{

        // 1. 获取Cipher对象
        Cipher cipher = Cipher.getInstance(transformation);

        // 2. 指定密钥规则
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);

        // 3. 解密初始化
        cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);

        // 4. 解密
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(encryptString));
        return new String(bytes);
    }

    // DES加密
    private static String desEncrypt(String source,String key,String transformation,String algorithm) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

        Cipher cipher = Cipher.getInstance(transformation);

        // 指定密钥规则(传递密钥字节码 和 加密算法)
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);

        // 加密初始化(加密模式，密钥规则)
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 执行加密
        byte[] bytes = cipher.doFinal(source.getBytes());

        // 输出加密后的密文
        String encryptString = Base64.getEncoder().encodeToString(bytes);
        return encryptString;

    }
}
